package com.example.aigc_education.integration.impl;


import com.example.aigc_education.common.BusinessException;
import com.example.aigc_education.integration.ChatServiceIntegration;
import com.example.aigc_education.integration.request.ChatMessageRequest;
import com.example.aigc_education.rpc.api.ChatServiceGrpc;
import com.example.aigc_education.rpc.api.ChatServiceProto;
import com.example.aigc_education.utils.JsonUtils;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
@Slf4j
public class ChatServiceIntegrationImpl implements ChatServiceIntegration {

    @GrpcClient("ai-algo-service")
    private ChatServiceGrpc.ChatServiceStub chatServiceStub;

    @GrpcClient("ai-algo-service")
    private ChatServiceGrpc.ChatServiceBlockingStub chatServiceBlockingStub;


    @Override
    public void stream (ChatMessageRequest request, StreamObserver<ChatServiceProto.ChatMessage> responseObserver) {
        try {
            // 构建用户消息
            ChatServiceProto.ChatMessage userMessage = ChatServiceProto.ChatMessage.newBuilder()
                    .setContent(request.getContent())
                    .setRole(ChatServiceProto.Role.USER)
                    .setChunkResp(request.isChunkResp())
                    .setUserId(request.getUserId())
                    .setConvId(request.getConvId())
                    .setMessageId(request.getMessageId())
                    .build();
            chatServiceStub.stream(userMessage, responseObserver);
            log.info("ChatServiceIntegrationImpl-stream chat success");
        } catch (Exception e) {
            throw new BusinessException("ChatServiceIntegrationImpl-stream chat message error");
        }
    }


    @Override
    public ChatServiceProto.ChatMessage invoke(ChatServiceProto.ChatMessage userMessage) {
        try {
            ChatServiceProto.ChatMessage chatMessage = chatServiceBlockingStub.invoke(userMessage);
            log.info("ChatServiceIntegrationImpl-Invoke chat success");
            return chatMessage;
        } catch (Exception e) {
            throw new BusinessException("ChatServiceIntegrationImpl-Invoke chat message error");
        }
    }
}
